﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Web.Security;

namespace TireService.Web.View.AdminView
{
    public partial class ManageUsers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            BindUsers(db);

            // Bind data for popup action controls
            ddlCustomer.DataSource = db.GetCustomers().Where(p => p.UserId == null);
            ddlCustomer.DataBind();
        }

        public void BindUsers(TireServiceDB db)
        {
            var users = from p in db.aspnet_Users
                        join v in db.aspnet_Memberships on p.UserId equals v.UserId into pv
                        from x in pv.DefaultIfEmpty()
                        join z in db.Customers on p.UserId equals z.UserId into pz
                        from y in pz.DefaultIfEmpty()
                        //join c in db.aspnet_UsersInRoles on p.UserId equals c.UserId into pc
                        //from d in pc.DefaultIfEmpty()
                        select new
                        { 
                            p.UserId,
                            p.UserName,
                            p.LastActivityDate,
                            x.Email,
                            x.IsLockedOut,
                            x.CreateDate, 
                            x.LastLoginDate, 
                            x.LastLockoutDate,
                            CustomerName = y.Name,
                            Roles = db.aspnet_UsersInRoles.Where(d => d.UserId == p.UserId).Count()
                        };

            gvUser.DataSource = users.ToList();
            gvUser.DataBind();
        }


        #region Control Functions

        protected void callbackCreateUserPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            try
            {
                // Get values from client 
                // CreateInternalUser - values: (0: CreateInternalUser , 1: Username and Email, 2: Password, 3: Send email to user (true/false), 5: Admin role (true/false), 6: Casehandler role (true/false), 7: Technician role (true/false))
                // CreateCustomerUser - values: (0: CreateCustomerUser, 1: Username and Email, 2: Password, 3: Send email to user (true/false), 4: CustomerId, 5: Business customer (true/false))
                string[] param = e.Parameter.Split('|');

                //int ServiceCarScheduleDetailId = Convert.ToInt32(param[0]);

                if (param[0].ToString() == "CreateInternalUser")
                {
                    // Create new user
                    MembershipUser newuser = Membership.CreateUser(param[1].ToString(), param[2].ToString(), param[1].ToString());

                    // Add user to customer role
                    if (Convert.ToBoolean(param[5]))
                    {
                        Roles.AddUserToRole(newuser.UserName, "Administrator");    
                    }
                    if (Convert.ToBoolean(param[6]))
                    {
                        Roles.AddUserToRole(newuser.UserName, "Sagsbehandler");
                    }
                    if (Convert.ToBoolean(param[7]))
                    {
                        Roles.AddUserToRole(newuser.UserName, "ServiceTekniker");
                    }

                    if (Convert.ToBoolean(param[3]))
                    {
                        // Prepare email
                        EmailNotificationServices emailService = new EmailNotificationServices();

                        
                        // TODO: Write code for sending emails to none customer users
                    }
                }

                if (param[0].ToString() == "CreateCustomerUser")
                {
                    TireServiceDB db = new TireServiceDB();

                    // Get customer
                    Customer customer = db.GetCustomer(Convert.ToInt32(param[4]));
                    
                    if (customer == null)
	                {
                        throw new ArgumentException("Kunde ikke fundet");
	                }

                    if (customer.UserId != null)
                    {
                        throw new ArgumentException("Kunde har allerede et brugerlogin: " + Membership.GetUser((object)customer.UserId).UserName);
                    }
                    else
                    {
                        // Create new user
                        MembershipUser newuser = Membership.CreateUser(param[1].ToString(), param[2].ToString(), param[1].ToString());

                        if (Convert.ToBoolean(param[5]))
                        {
                            // Business customer
                            // Add user to business customer role
                            Roles.AddUserToRole(newuser.UserName, "Erhvervskunde");
                        }
                        else
                        {
                            // Add user to customer role
                            Roles.AddUserToRole(newuser.UserName, "Kunde");
                        }

                        customer.UserId = new Guid(newuser.ProviderUserKey.ToString());

                        db.SubmitChanges();

                        if (Convert.ToBoolean(param[3]))
                        {
                            // Prepare email
                            EmailNotificationServices emailService = new EmailNotificationServices();

                            // Send email to user with user information
                            emailService.Customer_UserInformation_SendCustomerEmail(customer.Email, customer.Name, newuser.UserName, param[2].ToString(), customer.CustomerId);    
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }

        protected void callbackResetUserPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            try
            {
                // Get values from client (0: Username, 1: New Password, 2: Send email til bruger med login)
                string[] param = e.Parameter.Split('|');

                string username = param[0].ToString();
                string newpass = param[1].ToString();

                MembershipUser user = Membership.GetUser(username);

                if (user.IsLockedOut)
                {
                    user.UnlockUser();
                }

                // Set user password to random temporary password
                string newtemppass = user.ResetPassword();

                // Set user password to wanted one
                user.ChangePassword(newtemppass, newpass);

                // Check if system should send info to user
                if (Convert.ToBoolean(param[2]))
                {
                    TireServiceDB db = new TireServiceDB();
                    
                    Customer customer = db.GetCustomer(new Guid(user.ProviderUserKey.ToString()));
                    if (customer != null)
                    {
                        EmailNotificationServices emailService = new EmailNotificationServices();
                        emailService.UserInformation_SendCustomerEmail(user.Email, customer.Name, user.UserName, newpass, customer.CustomerId);
                    }
                    else
                    {
                        // TODO: Create function for sending email to none customer users
                    }
                    
                }
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }

        protected void callbackChangeUserRoleAssignmentPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            try
            {
                // TODO: Implement function
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.Value == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.Value == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.Value == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.Value == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        #endregion

    }
}